package com.zhz.project.main.socolar.wenzhang.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.zhz.project.common.util.alibaba.StringUtil;
import com.zhz.project.common.util.result.Result;
import com.zhz.project.common.util.result.ResultSupport;
import com.zhz.project.main.socolar.issue.SocolarIssueParser;
import com.zhz.project.main.socolar.issue.SocolarIssueRecord;
import com.zhz.project.main.socolar.issue.SocolarYearRecord;
import com.zhz.project.util.getWebContent;

public class GetCookieKey {
    private static Log   logger        = LogFactory.getLog(GetCookieKey.class);

    public static String TEST_URL      = "http://www.socolar.com/vn.aspx?id=11968";
    public static String CODE_GIF_URL  = "http://www.socolar.com/vc.aspx";
    public static String SITE_URL      = "";
    public static String CODE_POST_URL = "http://www.socolar.com/cc.aspx?h=";

    public static void main(String[] args) {
        GetCookieKey.verify();
    }

    public static Result verify() {
//    	System.out.println("thread=" + Thread.currentThread().getId() + "---getKeyAndCookie---start---");
        Result result = new ResultSupport(false);
//        logger.info("thread=" + Thread.currentThread().getId() + "---getKeyAndCookie---start---");

        HttpClient client = new HttpClient();

        HttpMethod method = new GetMethod(TEST_URL);
        try {

            List<Header> headers = new ArrayList<Header>();
            headers
                .add(new Header("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"));
            client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
            client.getHostConfiguration().setProxy(getWebContent.proxy, getWebContent.port);

            client.executeMethod(method);

            // 查看 cookie 信息
            CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
            Cookie[] cookies = cookiespec.match("www.socolar.com", 80, "/", false, client
                .getState().getCookies());

            String cookieValue = cookies[0].getValue();

            //返回的内容，即还有期刊的详情页面，含有卷期列表，
            String content = method.getResponseBodyAsString();

            SocolarIssueParser parser = new SocolarIssueParser();
            parser.setContent(content);

            List<SocolarYearRecord> socolarYearRecordList = parser.parse();
            String key = "";
            String testIssueUrl = "";
            //解析出其中第一个卷期的地址，获取其key值
            if (socolarYearRecordList != null && socolarYearRecordList.size() > 0) {
                SocolarYearRecord socolarYearRecord = socolarYearRecordList.get(0);
                List<SocolarIssueRecord> socolarIssueRecordList = socolarYearRecord
                    .getSocolarIssueRecordList();
                if (socolarIssueRecordList != null && socolarIssueRecordList.size() > 0) {

                    SocolarIssueRecord socolarIssueRecord = socolarIssueRecordList.get(0);
                    testIssueUrl = SITE_URL + socolarIssueRecord.getUrl();

                    key = StringUtil.substring(socolarIssueRecord.getUrl(),
                        StringUtil.indexOf(socolarIssueRecord.getUrl(), "&key") + 5);
                }
            }

            /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
            //上面已经解析出cookie和key值，下面要进行验证码获取和提交

            //访问第一个卷期的地址，此时应该是到输入验证码的页面，
            //验证码页面的内容
            content = getWebContent.getSocolarContentHttpURLConnection(testIssueUrl, cookieValue,
                false);
            //获取验证码图片，保存到本地
            String targetFilePath = getWebContent.getSocolarContentHttpURLConnection(CODE_GIF_URL,
                cookieValue, true);
//            System.out.println(targetFilePath);
            //将验证码图片提交到OCR服务器，获取验证码内容
            String code = getTxtCode(targetFilePath);
            if (StringUtil.contains(code, "_")) {
                //                logger.error("---error_code---");
                //                logger.error(code);
            }

            //已经获取到code，下面将该code发送到服务器端则可以访问

            String post_url = CODE_POST_URL + testIssueUrl;

            boolean ok = PostTxtCodeToServerClient.check(post_url, code, cookieValue, post_url);
            result.setSuccess(ok);
            result.getModels().put("key", key);
            result.getModels().put("cookie", cookieValue);
            //释放连接
            method.releaseConnection();

            return result;
        } catch (Exception e) {
            logger.error("---getKeyAndCookie---Exception", e);
            return result;
        }
    }

    private static String getTxtCode(String targetFilePath) {
        PostFileToServerClient code = new PostFileToServerClient();
        try {
            return code.getTxtCode(targetFilePath);
        } catch (Exception e) {
            logger.error("---getTxtCode---Exception", e);
            return "";
        }
    }

}
